package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    //    新增用户信息
    @PostMapping("/add")
    public Result add(@RequestBody User user){
        try {
            userService.save(user);
        }catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据异常");
            }else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }

    //修改用户信息
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        userService.updateUserAndAudit(user);
        return Result.success();
    }
    //删除用户
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        User currentUser = TokenUtils.getCurrentUser();
        if (id.equals(currentUser.getId())) {
            throw new ServiceException("不能删除当前的用户");
        }
        userService.removeById(id);
        return Result.success();
    }

    //批量删除
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids){
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser!=null && currentUser.getId()!=null &&ids.contains(currentUser.getId())) {
            throw new ServiceException("不能删除当前的用户");
        }
        userService.removeBatchByIds(ids);
        return Result.success();
    }

    //查询全部用户信息
   @GetMapping("/selectAll")
    public Result selectAll(){
       List<User> userList = userService.list(new QueryWrapper<User>().orderByDesc("id"));  //select * from user order by id desc
       return Result.success(userList);
    }

    //根据ID查询用户信息
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id){
        User user = userService.getById(id);
        return Result.success(user);
    }

    //根据ID查询用户信息
    //    根据条件查询的时候，如果不确定返回的结果有几个，那就统一返回一个List对象集合，这样最稳妥
    //    否则会出现 Expected one result (or null) to be returned by selectOne(), but found: 2
//    @GetMapping("/selectByName/{name}")
//    public Result selectById(@PathVariable String name){
//        List<User> userList = userService.selectByName(name);
//        return Result.success(userList);
//    }

    //多条件查询用户信息
//    @GetMapping("/selectByMore")
//    public Result selectByMore(@RequestParam String username,@RequestParam String name){
//        List<User> userList = userService.selectByMore(username ,name);
//        return Result.success(userList);
//    }

    //多条件查询用户信息
//    @GetMapping("/selectByMo")
//    public Result selectByMo(@RequestParam String username,@RequestParam String name){
//        List<User> userList = userService.selectByMo(username ,name);
//        return Result.success(userList);
//    }

    //多条件分页模糊查询用户信息
    @GetMapping("/selectByPage")
    public Result selectByPage( @RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam String username,
                                @RequestParam String name){
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(username), "username" ,username);
        queryWrapper.like(StrUtil.isNotBlank(name), "name" ,name);
        // select *from user where username like '%#{username}%' and name like '%#{name}%'
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }



}
